<?php

/**
 * This is the model class for table "{{category}}".
 *
 * The followings are the available columns in table '{{category}}':
 * @property integer $id
 * @property string $name
 * @property string $url
 * @property integer $parent_id
 * @property integer $status
 * @property integer $rank
 * @property integer $type
 * @property integer $icon
 */
class Category extends MyARContent
{

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Category the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{category}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
        return array(
            array('parent_id, status,', 'required'),
            array('parent_id, status, rank, type', 'numerical', 'integerOnly' => true),
            array('name, url,meta_desc,meta_key,seo_title,icon', 'length', 'max' => 250),
            // The following rule is used by search().
// Please remove those attributes that should not be searched.
            array('icon,id, name,meta_desc,meta_key,seo_title, url, parent_id, status, rank, type', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
        $relations              = parent::relations();
        $relations['childrent'] = array(self::HAS_MANY, 'Category', 'parent_id');
        $relations['product']   = array(self::HAS_MANY, 'Product', 'c_id', 'order' => 'status DESC,rank desc, id DESC', 'limit' => '8');
        $relations['parent']    = array(self::BELONGS_TO, 'Category', 'parent_id');
        return $relations;
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        $array = array(
            'id'            => 'ID',
            'name'          => 'Name',
            'url'           => 'Url',
            'parent_id'     => 'Parent',
            'status'        => 'Status',
            'rank'          => 'Rank',
            'type'          => 'Type',
            'icon'          => 'Icon',
            'meta_desc'     => 'Meta Desc',
            'meta_keywords' => 'Meta Keywords',
            'seo_title'     => 'Seo Title',
        );
        foreach ($array as $key => $val)
        {
            $array[$key] = Yii::t('sub_all', $val);
        }

        return $array;
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
// Warning: Please modify the following code to remove attributes that
// should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('name', $this->name, true);
        $criteria->compare('url', $this->url, true);
        $criteria->compare('parent_id', $this->parent_id);
        $criteria->compare('status', $this->status);
        $criteria->compare('rank', $this->rank);
        $criteria->compare('type', $this->type);
        $criteria->compare('icon', $this->icon, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    public static function getPublicArrayForCat($blacklist = array())
    {
        $root  = array(
            0 => Yii::t('category', 'Root category')
        );
        $array = $root + self::getSubCate(0, $blacklist);
        return $array;
    }

    public static function getPublicArray($blacklist = array())
    {
        $root  = array(
            '' => Yii::t('category', 'Root category')
        );
        $array = $root + self::getSubCate(0, $blacklist);
        return $array;
    }

    static function getSubCate($parent_id, $blacklist = array(), $separated = "|-- ")
    {
        $cri            = new CDbCriteria;
        $cri->condition = "status!=0 AND parent_id=:parent";
        $cri->params    = array(
            ':parent' => $parent_id,
        );
        $children       = self::model()->findAll($cri);

        /* Lay danh sach cac thu muc con */
        $array = array();
        foreach ($children as $child)
        {
            if (in_array($child->id, $blacklist))
                continue;
            $array[$child->id] = $separated . $child->name;
            $childArray        = self::getSubCate($child->id, $blacklist, $separated . "|-- ");
            if (!empty($childArray))
            {
                $array = $array + $childArray;
            }
        }
        return $array;
    }

    /**
     * Lấy các phần tử Danh mục thành một mảng, sử dụng cho form bài viết khi chọn
     * danh mục hoặc form Danh mục khi chọn danh mục cha
     * 
     * @param array $blacklist Mảng các id của những category không muốn hiển thị trong ds này
     * @return array Một mảng các category với key là id, value là name
     */
    public static function getPublicMenuArray($blacklist = array())
    {
        $array = self::getSubMenu(0, $blacklist);
        return $array;
    }

    static function getSubMenu($parent_id, $blacklist = array(), $separated = "|-- ")
    {
        $cri            = new CDbCriteria;
        $cri->condition = "status!=0 AND parent_id=:parent";
        $cri->params    = array(
            ':parent' => $parent_id,
        );
        $children       = self::model()->findAll($cri);

        /* Lay danh sach cac thu muc con */
        $array = array();
        foreach ($children as $child)
        {
            if (in_array($child->id, $blacklist))
                continue;
            $array[$child->id] = array(
                'text' => $separated . $child->name,
                'name' => $child->name,
            );
            $childArray        = self::getSubMenu($child->id, $blacklist, $separated . "|-- ");
            if (!empty($childArray))
            {
                $array = $array + $childArray;
            }
        }
        return $array;
    }

    public function getPublicUrl($absolute = false)
    {
        if ($absolute == FALSE)
        {
            return Yii::app()->createUrl("project/index", array(
                        'url' => $this->url,
            ));
        }
        else
        {
            return Yii::app()->createAbsoluteUrl("project/index", array(
                        'url' => $this->url,
            ));
        }
    }

    public function getTitleSeo()
    {
        if ($this->seo_title)
        {
            return $this->seo_title;
        }
        else
        {
            return $this->name;
        }
    }

    /*
     * BOX LIST CATEGORY frontend
     */

    public static function getShowAllCate()
    {
        $cri            = new CDbCriteria;
        $cri->condition = "parent_id=:parent and status > :s";
        $cri->params    = array(
            ':parent' => 0,
            ':s'      => self::STATUS_DRAFT
        );
        $cri->order     = 'rank DESC, id DESC';
        $cates          = Category::model()->findAll($cri);
        foreach ($cates as $cate)
        {
            self::getCateItem($cate);
        }
    }

    public static function getCateItem($cate)
    {
        $count = count($cate->product) != 0 ? '(<b>' . count($cate->product) . '</b>)' : null;
        if (!empty($cate->childrent))
        {
            echo "<li class='has-sub'><a href='$cate->publicUrl'>$cate->name $count</a>\n";
            echo "<ul>\n";
            foreach ($cate->childrent as $subcate)
            {
                self::getCateItem($subcate);
            }
            echo "</ul>\n";
            echo "</li>\n";
        }
        else
        {
            echo "<li><a href='$cate->publicUrl'>$cate->name $count</a></li>\n";
        }
    }

    static function getSubCateById($parent_id)
    {
        $cri            = new CDbCriteria;
        $cri->condition = "status!=0 AND parent_id=:parent ";
        $cri->params    = array(
            ':parent' => $parent_id,
        );
        $children       = self::model()->findAll($cri);

        /* Lay danh sach cac thu muc con */
        $array = array();
        foreach ($children as $child)
        {
            $array[]    = $child->id;
            $childArray = self::getSubCateById($child->id);
            if (!empty($childArray))
            {
                $array = $array + $childArray;
            }
        }
        $array[] += $parent_id;
        return $array;
    }

    /* Lấy các dự án liên quan */

    public static function getAllCateByCateId($cate = 0)
    {
        $criteria = new CDbCriteria();
        if ($cate->parent_id == 0)
        {
            $criteria->condition = 'status!=:st';
            $criteria->params    = array(
                ':st' => Product::STATUS_DRAFT,
            );
            $criteria->addInCondition('c_id', Category::getSubCateById($cate->id));
        }
        else
        {
            $criteria->condition = 'status!=:st and c_id=:cate';
            $criteria->params    = array(
                ':cate' => $cate->id,
                ':st'   => Product::STATUS_DRAFT,
            );
        }
        $criteria->limit = 6;
        $criteria->order = 'status DESC , id DESC';
        return Product::model()->findAll($criteria);
    }

}
